package cn.tedu.knows.faq.controller;

import cn.tedu.knows.commons.exception.ServiceException;
import cn.tedu.knows.commons.model.Answer;
import cn.tedu.knows.faq.service.IAnswerService;
import cn.tedu.knows.faq.vo.AnswerVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2021-10-27
 */
@RestController
@RequestMapping("/v2/answers")
@Slf4j
public class AnswerController {
    @Autowired
    private IAnswerService answerService;

    @PostMapping("")
    //@PreAuthorize("hasAuthority('/question/answer')")或者
    //hasRole 是特指验证角色的指令
    //ROLE_开头的auth就是角色的标识
    //hasRole验证时可以将ROLE_省略直接写他后面的内容
    //但是他的判断也不死板hasRole('ROLE_TEACHER')也可以
    @PreAuthorize("hasRole('TEACHER')")
    public Answer postAnswer(
            @Validated AnswerVo answerVo,
            BindingResult result,
            @AuthenticationPrincipal UserDetails user
            ){
        log.debug("表单信息:{}",answerVo);
        if (result.hasErrors()){
            String msg=result.getFieldError().getDefaultMessage();
            throw new ServiceException(msg);
        }
        //这里调用业务逻辑层方法
        Answer answer = answerService.saveAnswer(answerVo,user.getUsername());
        return answer;
    }

    @GetMapping("/question/{id}")
    public List<Answer> questionAnswer(
            @PathVariable Integer id
    ){
        List<Answer> answers = answerService.getAnswerByQuestionId(id);
        return answers;
    }

    //采纳回答的控制层代码
    @GetMapping("/{answerId}/solved")
    public String solved(
            @PathVariable Integer answerId,
            @AuthenticationPrincipal UserDetails user
    ){
        boolean accepted = answerService.accept(answerId,user.getUsername());
        if (accepted){
            return "ok";
        }else {
            return "必须是问题的提问者才能采纳回答";
        }
    }

}
